package org.jeecg.modules.cascv.image.service.merge.shipingui;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.TaskExecutePool;
import org.jeecg.modules.cascv.image.service.merge.ImageService;
import org.jeecg.modules.cascv.image.util.LaptopConstant;
import org.jeecg.modules.cascv.image.util.LaptopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author;作者
 * @Date 2023/2/13 15:26
 * @Description :
 * @Version
 */
@Slf4j
@Service
public class ShipinzhuguiZhaiXianKuanService extends ImageService {
    @Value("${imageurl}")
    private String imageurl;
    @Autowired
    private TaskExecutePool taskExecutePool;

    @Override
    public String idsNames() {
        return "6D1DH_32H,6D3DH_32H";
    }

    @Override
    public Result<Object> merge(JSONObject jsonObject, String idsName, String key) {
        JSONObject conJson = jsonObject.getJSONObject("Content");

        //打印报错不连续的包序号
        String packageNum = conJson.getString(LaptopConstant.Package_number_MAP.get(idsName));
        int intpackageNum = Integer.parseInt(packageNum.split(";")[1]);
        Integer lastPackageNum = LaptopConstant.packageNumMap.get(key);

        if (null == lastPackageNum) {
            LaptopConstant.packageNumMap.put(key, intpackageNum);
        } else {
            LaptopConstant.packageNumMap.put(key, intpackageNum);
            if (lastPackageNum + 1 != intpackageNum) {
                if (2511 != lastPackageNum && 0 != intpackageNum) {
                    log.error("图像丢包，包序号不连续，当前包的包序号:" + intpackageNum + "，上一包包序号:" + lastPackageNum);
                }
            }
        }


        String secondStr = jsonObject.getString("second");
        long second = Long.parseLong(secondStr);
        String subSecondStr = jsonObject.getString("subsecond");
        secondStr = LaptopUtil.toDayHoursMinSec(second);
        String dataFrames = conJson.getString(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
        String startEndFlag = conJson.getString(LaptopConstant.STARTEND_FLAG_MAP.get(idsName));
        dataFrames = dataFrames.substring(7, dataFrames.length() - 10);
        startEndFlag = startEndFlag.split(";")[0];
        StringBuilder queue = LaptopConstant.imageData.get(key);

        composite(idsName, key, conJson, dataFrames, queue, startEndFlag, secondStr, subSecondStr);

        return null;
    }

    private boolean composite(String idsName, String key, JSONObject content, String dataFrames, StringBuilder queue, String startEndFlag, String secondStr, String subSecondStr) {
        int width = 1280;
        int height = 1024;
        int k = 0;
        int[] intBuffer = new int[width * height];
//        if (LaptopConstant.START_FLAG.equals(startEndFlag)||!LaptopConstant.END_FLAG.equals(startEndFlag)) {
//            if (null == queue) {
//                queue = new StringBuilder();
//                queue = queue.append(dataFrames);
//
//            } else {
//                queue = queue.append(dataFrames);
//            }
//            LaptopConstant.imageData.put(key, queue);
//
//        } else if (LaptopConstant.END_FLAG.equals(startEndFlag)) {
        if (LaptopConstant.START_FLAG.equalsIgnoreCase(startEndFlag)) {
            return false;
        }
        if (null == queue) {
            queue = new StringBuilder();
            queue = queue.append(dataFrames);
        } else {
            queue = queue.append(dataFrames);
        }
        LaptopConstant.imageData.put(key, queue);


        if (LaptopConstant.END_FLAG.equalsIgnoreCase(startEndFlag)) {
            // queue.append(dataFrames);

            for (int j = 0; j < queue.length(); j += 2) {
                intBuffer[k++] = Integer.parseInt(queue.substring(j, j + 2), 16);
            }


            CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {

                long start = System.currentTimeMillis();
                byte[] byteArr = new byte[intBuffer.length];
                for (int i = 0; i < intBuffer.length; i++) {
                    byteArr[i] = (byte) intBuffer[i];
                }
                if (byteArr.length < height * width) {
                    return null;
                }
                String idStr = IdWorker.getIdStr();
                int png = LaptopConstant.nativeImageIO.write(byteArr, height, width, "/data/images/", idStr + ".png", "png");
                String imageUrl = "http://" + imageurl + "/jeecg-boot/test/gmvVideo/getImage/" + idStr + ".png";
                content.put("imageUrl", imageUrl);
                System.out.println("imageUrl = " + imageUrl);
                content.put("idsName", idsName);

                // String secondStr = content.getString("A1_FPR_MICU_APP1DATA_8_11_1").split(";")[1];
                //String subSecondStr = content.getString("A1_FPR_MICU_APP1DATA_12_13_1").split(";")[1];

                String[] split = secondStr.split(":");
                content.put("ts", split[0] + "天" + split[1] + "时" + split[2] + "分" + split[3] + "秒" + subSecondStr + "微秒");
                content.remove(LaptopConstant.FRAME_FIELD_MAP.get(idsName));
                content.put("key", key);
                log.info("时频柜主柜窄线宽"+idsName+"合成一张图片消耗时间：" + (System.currentTimeMillis() - start) + "毫秒");

                return content;
            }, taskExecutePool.threadPoolTaskExecutor2());
            LaptopConstant.imageFutureList.add(future);

            LaptopConstant.imageData.remove(key);
        }
        return true;
    }
}
